from flask import Blueprint
from application.models.users.user import User
user_blue = Blueprint("userblue",__name__)
# @user_blue.route("/reg")
# def reg():
#     res = User.query.all()
#     print(res)
#     return '欢迎使用flask'
from flask import Blueprint, jsonify, send_file, g
from util.myjwt import myjwt
from util.sms_code import SmsSDK
from flask_restful import Api, Resource, reqparse
# from application.models.users import *
# from captcha.image import ImageCaptcha
# from werkzeug.security import generate_password_hash, check_password_hash
import random, redis, string, jwt, time, re
# # 创建蓝图
lt_bp = Blueprint("views", __name__)
# # 给当前蓝图创建api对象
from db import db
api = Api(lt_bp)
#   获取图片验证码
from flask import Blueprint, make_response, jsonify
user_bp = Blueprint('user', __name__)
from util.myredis import r
from flask import request
import random, re
# 获取图片验证码
# class Syzm(Resource):
#     def get(self):
#         uuid=request.args.get('uuid')
#         yzm=str(random.randint(10000,99999))
#         cap=ImageCaptcha()
#         r.str_setex(uuid, 200,yzm)
#         img_code=cap.generate(yzm)
#         return send_file(img_code,mimetype='png')

# 获取数字验证码
# class Ssms_code(Resource):
#     def get(self):
#         mobile = request.args.get('mobile')
#         smsyzm = request.args.get('smsyzm')
#         uuid = request.args.get('uuid')
#         print('mobile>>>', mobile)
#         print('smsyzm>>>', smsyzm)
#         print('uuuid2>>>', uuid)
#         if not all([mobile, smsyzm, uuid]):
#              return jsonify({"code": 400, 'msg': "字段不完整"})
#         if not re.findall(r'^1[3-9]\d{9}$', mobile):
#               return jsonify({"code": 400, 'msg': "格式错误"})
#         aaa = r.str_get(uuid)
#         print('ccc>>>>>>>', aaa)
#         if aaa:
#            aaa = aaa.decode()
#         else:
#             return jsonify({"code": 400, 'msg': "图片验证码过期"})
#         if aaa.lower() != smsyzm.lower():
#             return jsonify({"code": 400, 'msg': "图片验证码错误"})
#
#         r.list_push("smsmobile", mobile)
#         while True:
#             for i in range(2):
#                 len=r.list_len('smsmobile') # 获取长度
#                 print('>>>',len)
#                 if len > 0 or len < 2:     # 如果大于0说明里面有数据
#                     value = r.list_pop('smsmobile')     # 从队列里获取单挑数据
#                     print('value>>>>>>>>>>>',value)
#                     mobile=value.decode()           # 对手机号进行解密
#                     code=random.randint(1000,9999)  # 生成随机验证码
#                     res = send_message(mobile,code) # 调用容联云函数
#                     print(res)                      # 打印容联云验证码
#                     r.str_setex(mobile,60,code)     # 存入redis60秒
#                 time.sleep(1)                       # 沉睡8秒
#                 return  jsonify({"code":200,'msg':'发送成功'})

# 登录接口
class Sdl(Resource):
    def get(self):
     mobile = request.args.get('mobile')
     smscode = request.args.get("smscode")

     print('sjh>>>>>>>>>>>>',mobile)
     print("smscode>>>>>>>>>>>",smscode)
     if not all([mobile, smscode]):
        return jsonify({"code": 400, 'msg': "字段不完整"})

     if not re.findall(r'^1[3-9]\d{9}$', mobile):
        return jsonify({"code": 400, 'msg': "格式错误"})

     smscode2 = r.str_get(mobile)
     print("smscode2>>>>>>>>>>>",smscode2)
     if smscode2:
         smscode2 = smscode2.decode()
         print("smscode2>>>>>>>>>>>", smscode2)
         print('dxyzm>>>>',smscode)
     else:
        return jsonify({"code": 400, 'msg': "验证码过期"})
     if smscode2 != smscode:
        return jsonify({"code": 400, 'msg': "验证码错误"})
     r.del_key(mobile)
     sql = f"""select id from admin_user where mobile={mobile};"""
     aa = db.findone(sql)
     if aa == None:
        return jsonify({"code": 400, 'msg': "用户不存在"})
     else:
        data={"data":{'aaid':aa,'mobile':mobile,'exptime':int(time.time())}}
        token=myjwt.jwt_encode(data)
        print('aa>>>>>>>>>',aa['id'])# 用户表中的id
        print('token>>>>>',token)
        sqa = f"""select roleid from admin_user where id = {aa['id']}"""
        yhid=db.findAll(sqa)
        print("yhid>>>>",yhid[0]['roleid'])

        sqll = f"""select re.*,pre.name as pname from role_resource as rr left join resource as re on rr.resourceid = re.id left join resource as pre on pre.id=re.pid where rr.roleid ={yhid[0]['roleid']};"""
        res = db.findAll(sqll)
        list = []
        idlist = []
        for i in res:
            if i['pid'] not in idlist:
                list.append({'id': i['pid'], 'name': i['pname'], 'son': []})
                idlist.append(i['pid'])
        for j in res:
            for index, p in enumerate(list):
                if j['pid'] == p['id']:
                    list[index]['son'].append({"id": j['id'], "name": j['name'], 'url': j['url']})
        print("res>>>>>>",res)
        print("list>>>>>",list)
        return jsonify({"code": 200, 'msg': "登陆成功", 'token': token,'list':list})
api.add_resource(Sdl, '/login/')

# api.add_resource(Syzm,'/imgcode/')
# api.add_resource(Ssms_code,'/send_sms/')

# from qiniu import Auth
# class Sqnytoken(Resource):
#     def get(self):
#         #需要填写你的 Access Key 和 Secret Key
#         access_key = 'VWKXpfhRZSeT-SMMo4HEJ708LO6pd4rBBToTQv36'
#         secret_key = 'CpX7R__itUIcFNH-JQ2uop1Wu-syEoAQvlkhp0SR'
#         #构建鉴权对象
#         q = Auth(access_key, secret_key)
#         #要上传的空间
#         bucket_name = 'p8q'
#         #上传后保存的文件名
#         token = q.upload_token(bucket_name)
#         return jsonify({"code":200,'token':token})
# api.add_resource(Sqnytoken,'/token/')



